package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.lettuce.core.RedisClient;
import jodd.util.CollectionUtil;
import lombok.SneakyThrows;
import org.aspectj.lang.annotation.Around;
import org.checkerframework.checker.units.qual.A;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ManageServiceImpl implements ManageService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    private SpuImageMapper spuImageMapper;

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private SkuImageMapper skuImageMapper;

    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;

    @Autowired
    private RabbitService rabbitService;

    @Override
    public List<BaseCategory1> getBaseCategory1() {
        // select * from base_category1
        return baseCategory1Mapper.selectList(null);
    }

    @Override
    public List<BaseCategory2> getBaseCategory2(Long category1Id) {
        // select * from base_category2 where category1_id = ?
        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>().eq("category1_id",category1Id));
    }

    @Override
    public List<BaseCategory3> getBaseCategory3(Long category2Id) {
        // select * from base_category3 where category2_id = ?
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>().eq("category2_id",category2Id));

    }

    @Override
    public List<BaseAttrInfo> getBaseAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        // select * from base_attr_info where category_id = category1Id and category_level = 1
        // select * from base_attr_info where category_id = category2Id and category_level = 2
        // select * from base_attr_info where category_id = category3Id and category_level = 3
        // 引入mybatis中的动态标签
        // 后续的功能中有个需求：根据分类id，查询平台属性，平台属性值：
        List<BaseAttrInfo> baseAttrInfoList = baseAttrInfoMapper.selectBaseAttrInfoList(category1Id,category2Id,category3Id);
        return baseAttrInfoList;
    }

    // 添加或修改
    @Override
    @Transactional(rollbackFor = Exception.class) // 在方法体内发生异常的时候就会回滚
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //base_attr_info
        if(baseAttrInfo.getId()!=null){
            //修改操作
            baseAttrInfoMapper.updateById(baseAttrInfo);
        }else {
            baseAttrInfoMapper.insert(baseAttrInfo);
        }


        //base_attr_value 先删除平台属性id对呀的属性值数据，再新增
        QueryWrapper<BaseAttrValue> baseAttrValueQueryWrapper = new QueryWrapper<>();
        baseAttrValueQueryWrapper.eq("attr_id",baseAttrInfo.getId());
        baseAttrValueMapper.delete(baseAttrValueQueryWrapper);

        //获取平台属性值数据
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if(!CollectionUtils.isEmpty(attrValueList)){
            //循环遍历添加
            for (BaseAttrValue baseAttrValue : attrValueList) {
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(baseAttrValue);
            }
        }

    }

    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        //select * from base_attr_value where attr_id = ?
        List<BaseAttrValue> baseAttrValueList = baseAttrValueMapper.selectList(new QueryWrapper<BaseAttrValue>().eq("attr_id", attrId));
        return baseAttrValueList;
    }

    @Override
    public BaseAttrInfo getBaseAttrInfo(Long attrId) {
        //根据主键查询平台属性对象
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);
        //判断是否为空
        if(baseAttrInfo!=null){
            //select * from base_attr_value where attr_id = ?
            baseAttrInfo.setAttrValueList(getAttrValueList(attrId));
        }
        return baseAttrInfo;
    }

    @Override
    public IPage<SpuInfo> getPage(Page<SpuInfo> page, Long category3Id) {
        // 封装条件
        QueryWrapper<SpuInfo> spuInfoQueryWrapper = new QueryWrapper<>();
        spuInfoQueryWrapper.eq("category3_id",category3Id);
        spuInfoQueryWrapper.orderByDesc("id");
        // 需要两个参数，一个是page 当前页，每页显示条数   一个是wrapper条件
        spuInfoMapper.selectPage(page,spuInfoQueryWrapper);
        return page;
    }

    @Override
    public IPage<SpuInfo> getPages(Page<SpuInfo> page, SpuInfo spuInfo) {
        QueryWrapper<SpuInfo> spuInfoQueryWrapper = new QueryWrapper<>();
        spuInfoQueryWrapper.eq("category3_id",spuInfo.getCategory3Id());
        spuInfoQueryWrapper.orderByDesc("id");
        // 需要两个参数，一个是page 当前页，每页显示条数   一个是wrapper条件
        spuInfoMapper.selectPage(page,spuInfoQueryWrapper);
        return page;
    }

    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        List<BaseSaleAttr> baseSaleAttrList = baseSaleAttrMapper.selectList(null);
        return baseSaleAttrList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {

        spuInfoMapper.insert(spuInfo);

        //获取到spuImage集合数据
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        //判断不为空
        if(!CollectionUtils.isEmpty(spuImageList)){
            //循环遍历
            for (SpuImage spuImage : spuImageList) {
                //需要将spuId赋值
                spuImage.setSpuId(spuInfo.getId());
                //保存spuImage
                spuImageMapper.insert(spuImage);
            }
        }

        //获取销售属性集合
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        //判断
        if(!CollectionUtils.isEmpty(spuSaleAttrList)){
            for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
                //需要将spuId赋值
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);

                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                if(!CollectionUtils.isEmpty(spuSaleAttrValueList)){
                    for (SpuSaleAttrValue spuSaleAttrValue : spuSaleAttrValueList) {
                        //需要将spuId，sale_attr_name赋值
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    }
                }
            }
        }



    }

    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
        // select * from spu_image where spu_id = ?
        QueryWrapper<SpuImage> spuImageQueryWrapper = new QueryWrapper<>();
        spuImageQueryWrapper.eq("spu_id",spuId);
        List<SpuImage> spuImageList = spuImageMapper.selectList(spuImageQueryWrapper);
        return spuImageList;
    }

    @Override
    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
        // 不仅需要获取到销售属性名，还需要获取到销售属性值的名字  spu_sale_attr,spu_sale_attr_value
        List<SpuSaleAttr> spuSaleAttrList = spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
        return spuSaleAttrList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSkuInfo(SkuInfo skuInfo) {
        /*
            skuInfo
            skuAttrValue
            skuSaleAttrValue
            skuImage
         */
        //保存skuInfo
        skuInfoMapper.insert(skuInfo);
        //skuAttrValue
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if(!CollectionUtils.isEmpty(skuAttrValueList)){
            for (SkuAttrValue skuAttrValue : skuAttrValueList) {
                // 给skuId赋值
                skuAttrValue.setSkuId(skuInfo.getId());
                skuAttrValueMapper.insert(skuAttrValue);
            }
        }

        //skuSaleAttrValue
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        if(!CollectionUtils.isEmpty(skuSaleAttrValueList)){
            //循环遍历
            for (SkuSaleAttrValue skuSaleAttrValue : skuSaleAttrValueList) {
                // sku_id spu_id
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            }
        }
        //skuImage
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if(!CollectionUtils.isEmpty(skuImageList)){
            for (SkuImage skuImage : skuImageList) {
                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            }
        }
    }

    @Override
    public IPage<SkuInfo> getSkuInfoPage(Page page) {
        QueryWrapper<SkuInfo> skuInfoQueryWrapper = new QueryWrapper<>();
        skuInfoQueryWrapper.orderByDesc("id");
        skuInfoMapper.selectPage(page,skuInfoQueryWrapper);
        return page;
    }

    @Override
    public void onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);
        skuInfoMapper.updateById(skuInfo);

        // 在此发送一个消息，异步  有个监听者，调用upperGoods方法
        // 发送的消息主体是谁， 根据消息监听者业务逻辑有关系
        this.rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_UPPER,skuId);
    }

    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);
        skuInfoMapper.updateById(skuInfo);

        // 在此发送一个消息，异步  有个监听者，调用lowerGoods方法
        this.rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_LOWER,skuId);
    }

    @SneakyThrows
    @Override
    @GmallCache(prefix = "skuInfo:")
    public SkuInfo getSkuInfo(Long skuId) {
        //return getSkuInfoRedis(skuId);
        //return getSkuInfoRedisson(skuId);
        return getSkuInfoDB(skuId);
    }

    private SkuInfo getSkuInfoRedisson(Long skuId) {
        SkuInfo skuInfo = null;
        try {

            // skuInfo 数据key 这可key要保证唯一
            String skuKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
            // 通过key获取缓存中的数据
            skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);

            if(skuInfo == null){
                // 直接调用redisson的方法就可以了
                String lockKey = RedisConst.SKUKEY_PREFIX+ skuId +RedisConst.SKULOCK_SUFFIX;
                RLock lock = redissonClient.getLock(lockKey);

                // 上锁
                boolean result = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                if(result){
                    try {
                        // 业务逻辑
                        skuInfo = getSkuInfoDB(skuId);
                        // 判断skuInfo
                        if(skuInfo == null){
                            // 创建一个空对象
                            SkuInfo skuInfo1 = new SkuInfo();
                            // 放入缓存
                            redisTemplate.opsForValue().set(skuKey,skuInfo1,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
                            // 返回当前数据
                            return  skuInfo1;
                        }
                        // 放入缓存
                        redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SKUKEY_TIMEOUT,TimeUnit.SECONDS);
                        return skuInfo;
                    }finally {
                        lock.unlock();
                    }
                }else {
                    // 没有获取到分布式锁
                    // 睡一会儿，自旋
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return getSkuInfo(skuId);
                }
            }else {
                return skuInfo;
            }
        } catch (InterruptedException e) {
            // 记录日志，发送短信通知
            e.printStackTrace();
        }
        return getSkuInfoDB(skuId);
    }

    public SkuInfo getSkuInfoRedis(Long skuId){
        /* 1. 从缓存获取数据，必须知道skuInfo是以哪种数据类型进行存储的
            String: 变量，常量
            Hash:对象
            List:队列
            Set:获取两个结果集的交集，并集...
            ZSet:放在一个排序

            使用哪种
                Hsah：hset(key,field,value);
        */
        SkuInfo skuInfo = null;

        try {
            // skuInfo 数据key 这可key要保证唯一
            String skuKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
            // 通过key获取缓存中的数据
            skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);

            //判断
            if(skuInfo == null){
                //缓存中没有数据，从数据库获取，放入缓存，但是，有可能会造成缓存击穿，穿透
                // skuId = 47 击穿，skuId=147 穿透
                // 定义一个锁
                String lockKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKULOCK_SUFFIX;
                String uuid = UUID.randomUUID().toString();
                // 使用命令能否获取资源
                Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockKey, uuid, RedisConst.SKULOCK_EXPIRE_PX1, TimeUnit.SECONDS);
                if(flag){
                    // 获取到锁
                    skuInfo =  getSkuInfoDB(skuId);
                    // 判断skuInfo
                    if(skuInfo == null){
                        // 创建一个空对象
                        SkuInfo skuInfo1 = new SkuInfo();
                        // 放入缓存
                        redisTemplate.opsForValue().set(skuKey,skuInfo1,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
                        // 返回当前数据
                        return  skuInfo1;
                    }
                    // 放入缓存
                    redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SKUKEY_TIMEOUT,TimeUnit.SECONDS);

                    // 释放锁
                    //使用lua脚本保证删除操作的原子性
                    //第一个参数
                    DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                    //放入lua脚本字符串
                    redisScript.setScriptText(script);
                    //设置返回的类型
                    redisScript.setResultType(Long.class);
                    //第二个参数是key，第三个参数是value
                    redisTemplate.execute(redisScript, Arrays.asList(lockKey),uuid);
                    // 返回数据库中的数据
                    return skuInfo;
                }else {
                    // 没有获取到分布式锁
                    // 睡一会儿，自旋
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return getSkuInfo(skuId);
                }

            }else {
                // 直接返回即可
                return skuInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  getSkuInfoDB(skuId);
    }


    public SkuInfo getSkuInfoDB(Long skuId){
        //select * from sku_info where id = skuId
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if(skuInfo!=null){

            //可以将skuImageList查询出来放入skuInfo对象中
            // select * from sku_image where sku_id = skuId
            List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId));
            skuInfo.setSkuImageList(skuImageList);
        }
        return skuInfo;
    }

    @Override
    @GmallCache(prefix = "baseCategoryView:")
    public BaseCategoryView getBaseCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    @Override
    @GmallCache(prefix = "spuSaleAttrListCheckBySku:")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        /*
            select
                ssa.id,
                ssa.spu_id,
                ssa.base_sale_attr_id,
                ssa.sale_attr_name,
                ssav.id sale_attr_value_id,
                ssav.sale_attr_value_name,
                if(sav.sku_id is null,0,1) is_checked
            from spu_sale_attr ssa inner join spu_sale_attr_value ssav
               on ssa.spu_id = ssav.spu_id and ssa.base_sale_attr_id = ssav.base_sale_attr_id
                left join sku_sale_attr_value sav on sav.sale_attr_value_id = ssav.id
                    and sku_id = 44
            where ssa.spu_id = 28
            order by ssa.base_sale_attr_id,ssav.id
         */
        return spuSaleAttrMapper.selectSpuSaleAttrListCheckBySku(skuId,spuId);

    }

    @Override
    public BigDecimal getSkuPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if(skuInfo!=null){
            return skuInfo.getPrice();
        }else {
            return new BigDecimal(0);
        }
    }

    @Override
    @GmallCache(prefix = "skuValueIdsMap:")
    public Map getSkuValueIdsMap(Long spuId) {
        Map<Object,Object> hashMap = new HashMap<>();
        List<Map> mapList = skuSaleAttrValueMapper.selectSaleAttrValuesBySpu(spuId);
        for (Map map : mapList) {
            Object sku_id = map.get("sku_id");
            Object value_ids = map.get("value_ids");

            hashMap.put(value_ids,sku_id);
        }
        return hashMap;
    }

    @Override
    @GmallCache(prefix = "getBaseCategoryList:")
    public List<JSONObject> getBaseCategoryList() {
        List<JSONObject> list = new ArrayList<>();
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("index",1) //底层维护了Map

        // 先获取到所有的分类数据集合
        List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(null);

        // 找到哪些是一级分类数据 以一级分类id进行分组
        Map<Long, List<BaseCategoryView>> category1Map = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        // 定义一个index
        int index = 1;
        // 循环遍历map
        for (Map.Entry<Long, List<BaseCategoryView>> entry1 : category1Map.entrySet()) {
            Long category1Id = entry1.getKey();
            List<BaseCategoryView> category2List = entry1.getValue();
            // 声明一个1级分类对象
            JSONObject category1 = new JSONObject();
            category1.put("index",index);
            category1.put("categoryId",category1Id);
            category1.put("categoryName",category2List.get(0).getCategory1Name());
            // index 迭代
            index++;
            // 找到哪些是二级分类数据
            Map<Long, List<BaseCategoryView>> category2Map = category2List.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            // 声明一个集合来存储2级分类对象
            List<JSONObject> category2Child = new ArrayList<>();
            for (Map.Entry<Long, List<BaseCategoryView>> entry2 : category2Map.entrySet()) {
                Long category2Id = entry2.getKey();
                List<BaseCategoryView> category3List = entry2.getValue();
                // 声明一个2级分类对象
                JSONObject category2 = new JSONObject();
                category2.put("categoryId",category2Id);
                category2.put("categoryName",category3List.get(0).getCategory2Name());

                List<JSONObject> category3Child = new ArrayList<>();
                // 找到哪些是三级分类数据
                category3List.forEach((baseCategory3View)->{
                    // 声明一个3级分类对象
                    JSONObject category3 = new JSONObject();
                    category3.put("categoryId",baseCategory3View.getCategory3Id());
                    category3.put("categoryName",baseCategory3View.getCategory3Name());
                    category3Child.add(category3);
                });
                // 需要将每个2级分类添加到2级分类集合中
                category2.put("categoryChild",category3Child);
                category2Child.add(category2);

            }

            category1.put("categoryChild",category2Child);
            // 将当前的一级分类数据放入List集合
            list.add(category1);
        }




        return list;
    }

    @Override
    public BaseTrademark getTrademarkByTmId(Long tmId) {
        BaseTrademark baseTrademark = baseTrademarkMapper.selectById(tmId);
        return baseTrademark;
    }

    @Override
    public List<BaseAttrInfo> getAttrList(Long skuId) {
        List<BaseAttrInfo> baseAttrInfoList = baseAttrInfoMapper.selectAttrList(skuId);
        return baseAttrInfoList;
    }
}
